package org.iot.iotserver.service.impl;

import io.netty.channel.Channel;
import io.netty.channel.ChannelId;
import io.netty.channel.group.ChannelGroup;
import io.netty.util.AttributeKey;
import org.iot.iotserver.service.IIOTCommonService;

import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * channel 相关处理
 */
public class IOTCommonServiceImpl implements IIOTCommonService {

    private final ChannelGroup channels;

    public IOTCommonServiceImpl(ChannelGroup channels) {
        this.channels = channels;
    }

    public long getChannelSize() {
        return this.channels.size();
    }

    @Override
    public void addChannel(Channel channel) {
        this.channels.add(channel);
    }

    @Override
    public void removeChannel(ChannelId channelId) {
        this.channels.remove(channelId);
    }

    @Override
    public Optional<Channel> findFirstChannel(Predicate<Channel> predicate) {
        return channels.stream().filter(predicate).findFirst();
    }

    @Override
    public List<Channel> findChannels(Predicate<Channel> predicate) {
       return this.channels.stream().filter(predicate).collect(Collectors.toList());
    }

    @Override
    public void setAttr(ChannelId channelId, String attrKey, Object attr) {
        this.channels.find(channelId).attr(AttributeKey.valueOf(attrKey)).set(attr);
    }

    @Override
    public Object getAttr(ChannelId channelId, String attrKey) {
        return this.channels.find(channelId).attr(AttributeKey.valueOf(attrKey)).get();
    }

    @Override
    public Object removeAttr(ChannelId channelId, String attrKey) {
        Object attr = getAttr(channelId, attrKey);
        this.channels.find(channelId).attr(AttributeKey.valueOf(attrKey)).set(null);
        return attr;
    }

}
